﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Rotempco.BaseClass.Objects.Enums;
using Rotempco.Website.Logic;
using System.Collections.Specialized;
using Rotempco.Core.ORM.Objects;
using Rotempco.Core.Web.CRUD.Objects;
using Rotempco.Core.Web.CRUD.Objects.Enums;
using Rotempco.Core.Web.Logic;

namespace Rotempco.Website.MasterPages.UserControls
{
    public partial class DefaultMultiColumnPageList : System.Web.UI.UserControl
    {
        private const string defaultTableListCssClass = "defaultTableList";
        protected string tableListCssClass;
        protected string tabelListWidth;
        private PageListMultiColumnContainer DetailPageContainer;

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void SetDetailsList(PageListMultiColumnContainer detailPageContainer)
        {
            DetailPageContainer = detailPageContainer;

            repeater_Headers.DataSource = detailPageContainer.Headers;
            repeater_Headers.DataBind();

            repeater_Rows.DataSource = detailPageContainer.DetailRows;
            repeater_Rows.DataBind();

            if (detailPageContainer.ShowSumValues && detailPageContainer.DetailRows.Count > 0)
            {
                repeater_Footer.Visible = true;
                repeater_Footer.DataSource = detailPageContainer.SumValues;
                repeater_Footer.DataBind();
            }

            pagingPages_Content.PagingContainer = detailPageContainer.PagingContainer;

            tableListCssClass = string.IsNullOrWhiteSpace(detailPageContainer.TableListCssClass)
                                           ? defaultTableListCssClass
                                           : detailPageContainer.TableListCssClass;

            if (detailPageContainer.TableListWidthInPx != null)
                tabelListWidth = "width:" + detailPageContainer.TableListWidthInPx + "px";

        }

        protected void repeater_Headers_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                HeaderElement headerElement = e.Item.DataItem as HeaderElement;
                PlaceHolder placeHolder_Name = e.Item.FindControl("placeHolder_Name") as PlaceHolder;

                if (IsHeaderSortable(headerElement.SortTableName))
                {
                    HyperLink hyperLink_Name = new HyperLink();
                    hyperLink_Name.Text = headerElement.Name;
                    hyperLink_Name.Visible = IsHeaderSortable(headerElement.SortTableName);
                    hyperLink_Name.NavigateUrl = GetSortUrl(headerElement.SortTableName, headerElement.SortColumnName);

                    Image image_SortDirection = new Image();
                    image_SortDirection.ImageUrl = GetSortImage(headerElement.SortTableName, headerElement.SortColumnName);
                    image_SortDirection.AlternateText = "Sorter";
                    image_SortDirection.CssClass = "listSortImage";
                    placeHolder_Name.Controls.Add(hyperLink_Name);
                    placeHolder_Name.Controls.Add(image_SortDirection);
                }
                else
                {
                    Label label_Name = new Label();
                    label_Name.Text = string.IsNullOrWhiteSpace(headerElement.Name) ? "&nbsp" : headerElement.Name;
                    placeHolder_Name.Controls.Add(label_Name);
                }

                HtmlTableCell item_th = e.Item.FindControl("th_Item") as HtmlTableCell;
                item_th.Style.Add("text-align", Enum.GetName(typeof(AlignTypeEnum), headerElement.CellAlign));
                if (headerElement.CellWidthInPx != 0)
                {
                    item_th.Style.Add("width", headerElement.CellWidthInPx + "px");
                    ((HtmlControl)e.Item.FindControl("td_Div_ItemHeader")).Style.Add("width", (headerElement.CellWidthInPx - 24).ToString() + "px");
                }
            }
        }


        protected void repeater_Column_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                MultiColumnOptions multiColumnOptions = e.Item.DataItem as MultiColumnOptions;
                ((HtmlTableCell)e.Item.FindControl("td_Item")).Style.Add("text-align", Enum.GetName(typeof(AlignTypeEnum), multiColumnOptions.CellAlign));
                if (multiColumnOptions.CellWidthInPx != 0)
                    ((HtmlControl)e.Item.FindControl("td_Div_Item")).Style.Add("width", (multiColumnOptions.CellWidthInPx - 24).ToString() + "px");

                PlaceHolder placeHolder_Name = e.Item.FindControl("placeHolder_Name") as PlaceHolder;


                if (multiColumnOptions.LinkIcon != null)
                {
                    PlaceHolder placeHolder_Icon = e.Item.FindControl("placeHolder_Icon") as PlaceHolder;
                    string imageUrl = null;

                    switch (multiColumnOptions.LinkIcon)
                    {
                        case LinkIconEnum.Delete:
                            imageUrl = "/Images/CRUD/Delete.png";
                            break;
                        case LinkIconEnum.Edit:
                            imageUrl = "/Images/CRUD/Edit.png";
                            break;
                        case LinkIconEnum.SortUp:
                            imageUrl = "/Images/CRUD/SortArrowUp.png";
                            break;
                        case LinkIconEnum.SortDown:
                            imageUrl = "/Images/CRUD/SortArrowDown.png";
                            break;
                        case LinkIconEnum.Checkmark:
                            imageUrl = "/Images/CRUD/Checkmark.png";
                            break;
                        case LinkIconEnum.View:
                            imageUrl = "/Images/CRUD/View.png";
                            break;
                        default:
                            break;
                    }

                    if (!string.IsNullOrWhiteSpace(imageUrl))
                    {
                        Image image = new Image()
                        {
                            ImageUrl = imageUrl,
                            BorderStyle = BorderStyle.None,
                            ImageAlign = ImageAlign.Middle
                        };

                        placeHolder_Icon.Controls.Add(image);
                    }
                }

                if (multiColumnOptions.LinkOptions != null)
                {
                    if (multiColumnOptions.LinkOptions.Url != null)
                    {
                        HyperLink hyperLink_Name = new HyperLink();
                        hyperLink_Name.Text = multiColumnOptions.DisplayName ?? "&nbsp;";
                        hyperLink_Name.NavigateUrl = multiColumnOptions.LinkOptions.Url;
                        hyperLink_Name.Target = Enum.GetName(typeof(LinkTargetEnum), multiColumnOptions.LinkOptions.LinkTarget);
                        if (!string.IsNullOrWhiteSpace(multiColumnOptions.CssClass))
                            hyperLink_Name.CssClass = multiColumnOptions.CssClass;

                        if (multiColumnOptions.LinkOptions.ConfirmBeforeRedirect)
                        {
                            string script = "return confirm(' " + multiColumnOptions.LinkOptions.ConfirmMessage + "');";
                            hyperLink_Name.Attributes.Add("OnClick", script);
                        }

                        placeHolder_Name.Controls.Add(hyperLink_Name);
                    }
                    else
                    {
                        placeHolder_Name.Controls.Add(new LiteralControl("&nbsp;"));
                    }
                }
                else
                {
                    Label label_Name = new Label();
                    label_Name.Text = multiColumnOptions.DisplayName ?? "&nbsp;";
                    if (!string.IsNullOrWhiteSpace(multiColumnOptions.CssClass))
                        label_Name.CssClass = multiColumnOptions.CssClass;

                    placeHolder_Name.Controls.Add(label_Name);
                }

            }
        }

        protected void repeater_Footer_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                FooterElement footerElement = e.Item.DataItem as FooterElement;
                Label label_Value = e.Item.FindControl("label_Value") as Label;
                if (e.Item.ItemIndex == 0)
                {
                    label_Value.Text = "<strong>I alt</strong> ";
                }
                if (footerElement.Show)
                {
                    ((HtmlTableCell)e.Item.FindControl("td_Item")).Style.Add("text-align", Enum.GetName(typeof(AlignTypeEnum), footerElement.CellAlign));
                    label_Value.Text += "<strong>" + footerElement.Value.ToString() + "</strong>";
                }
                else
                {
                    label_Value.Text += "&nbsp;";
                }
            }
        }


        private static bool IsHeaderSortable(string sortTableName)
        {
            return !string.IsNullOrWhiteSpace(sortTableName);
        }


        private string GetSortUrl(string sortTablename, string sortColumnName)
        {
            NameValueCollection query = HttpUtility.ParseQueryString(Request.Url.Query);
            string decendingQuery = query["Descending"];

            if (
                (
                    (query["TableName"] == sortTablename && query["ColumnName"] == sortColumnName)
                    ||
                    (DetailPageContainer.PagingContainer.TableName == sortTablename && DetailPageContainer.PagingContainer.ColumnName == sortColumnName)
                )
                && query["Descending"] != "True")
                query["Descending"] = "True";
            else
                query["Descending"] = "False";

            if (DetailPageContainer.PagingContainer.DefaultSortOrderDecending == true && string.IsNullOrWhiteSpace(decendingQuery))
                query["Descending"] = "False";

            query["TableName"] = sortTablename;
            query["ColumnName"] = sortColumnName;

            return Request.Url.AbsolutePath + "?" + query.ToString();
        }


        private string GetSortImage(string sortTablename, string sortColumnName)
        {
            NameValueCollection query = HttpUtility.ParseQueryString(Request.Url.Query);

            if ((query["TableName"] == sortTablename && query["ColumnName"] == sortColumnName) ||
                (DetailPageContainer.PagingContainer.TableName == sortTablename && DetailPageContainer.PagingContainer.ColumnName == sortColumnName))
            {
                if (query["Descending"] == "True" || DetailPageContainer.PagingContainer.DefaultSortOrderDecending == true)
                    return "/Images/CRUD/SortArrowDown.png";
                else
                    return "/Images/CRUD/SortArrowUp.png";
            }

            return "/Images/CRUD/SortArrowNone.png";
        }
    }
}